<?php
/**
 * Created by PhpStorm.
 * User: 王松
 * Time: 2017/9/13 11:26
 */

namespace App\Project\Traits\Model;

use App\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Builder as QueryBuilder;

trait HasReception
{
    /**
     * 查询结果中添加 is_reception字段， 用于判断 $doctor是否接诊过
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \App\User                             $doctor
     * @return \Illuminate\Database\Query\Builder|static
     */
    public function scopeIsReception(Builder $builder, User $doctor)
    {
        return $builder->selectSub($this->receptionSql($doctor), 'is_reception');
    }

    /**
     * 用于添加 $doctor诊接过的患者 (where 条件)
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \App\User                             $doctor
     * @return \Illuminate\Database\Query\Builder
     */
    public function scopeHasReception(Builder $builder, User $doctor)
    {
        return $builder->isReception($doctor)->whereExists($this->receptionSql($doctor));
    }

    /**
     * 用于添加 $doctor未接诊过的患者 (where 条件)
     * @param \Illuminate\Database\Eloquent\Builder $builder
     * @param \App\User                             $doctor
     * @return \Illuminate\Database\Query\Builder|static
     */
    public function scopeHasNotReception(Builder $builder, User $doctor)
    {
        return $builder->isReception($doctor)->whereNotExists($this->receptionSql($doctor));
    }

    /**
     * @param \App\User $doctor
     * @return \Closure
     */
    protected function receptionSql(User $doctor)
    {
        return function (QueryBuilder $query) use ($doctor) {
            $query->select('st_medical_records.id as record_id')->from('st_medical_records')->where([
                'st_medical_records.doctor_id' => $doctor->id
            ])->whereRaw('`st_pools`.`patient_id` = `st_medical_records`.`patient_id`')->take(1);
        };
    }
}